#include "protocol.h"


void sendUdpPackage(const unsigned char *data, const int dataSize, const int sock, const struct sockaddr_in *rNetAddr)
{
	static socklen_t svrlen = sizeof(struct sockaddr_in);
	int ret = sendto(sock, data, dataSize, 0, (const struct sockaddr*)rNetAddr, svrlen);
	if (ret < dataSize)
	{
		std::cout << "sendto fail ! ret = " << ret << " sendPackageSize = " << dataSize << std::endl;
	}
}

void getLocalMacAddr(char *macAddr)
{
	FILE  *stream;
	char *p;
	int i;
	char   buf[1024];
	memset(buf, 0, sizeof(buf));
	stream = popen("ifconfig|grep HWaddr", "r");
	fread(buf, sizeof(char), sizeof(buf), stream);
	pclose(stream);
	p = strstr(buf, "HWaddr");
	if (!p)
	{
		memcpy(macAddr, "005056896dbd", 12);
		macAddr[13] = '\0';
		return;
	}

	p += strlen("HWaddr");
	p++;
	for (i = 0; i < CPU_ID_SIZE / 2; i++)
	{
		macAddr[i * 2] = p[i * 3];
		macAddr[i * 2 + 1] = p[i * 3 + 1];
	}
}

int getIpFromDomainName(char *ip, const char *domainName)
{
	struct hostent *host = gethostbyname(domainName);
	if (host == NULL)
	{
		std::cout << "can not get ip by domain name ! domain name = " << domainName << std::endl;
		return -1;
	}
	else
	{
		char *ipASCII = inet_ntoa(*(struct in_addr*)(host->h_addr));
		strcpy(ip, ipASCII);
		std::cout << domainName << "change into ip:" << ip << std::endl;
		return 0;
	}
}
